<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter,useRoute } from 'vue-router'
import { ArrowUp, ArrowDown, StarFilled, Refresh, ArrowLeft } from '@element-plus/icons-vue';
import { readingDataService } from '@/api/reading.js';
import * as echarts from 'echarts'

// 创建路由实例
const router = useRouter()

// 类型定义
interface GenreData {
  name: string
  value: number
  percentage: number
}

interface TimeData {
  time: string
  value: number
  percentage: number
}

// 数据状态
const totalBooks = ref(0)
const readingDays = ref(0)
const totalHours = ref(0)
const currentStreak = ref(0)
const booksTrend = ref(0)
const timeTrend = ref(0)
const currentMonth = ref('')
const efficiencyScore = ref(0)
const concentrationScore = ref(0)
const comprehensionScore = ref(0)
const speedScore = ref(0)
const timeRange = ref<'week' | 'month' | 'year'>('week')
const genreData = ref<GenreData[]>([])
const timeData = ref<TimeData[]>([])

// 图表引用
let trendChart: echarts.ECharts | null = null
let pieChart: echarts.ECharts | null = null

// 颜色配置
const colors = ['#2A5CAA', '#4ECB73', '#FFC107', '#FF6B6B', '#9C27B0']
const timeColors = ['#2A5CAA', '#4ECB73', '#FFC107', '#FF6B6B']

// 计算属性
const booksTrendIcon = computed(() => 
  booksTrend.value > 0 ? ArrowUp : booksTrend.value < 0 ? ArrowDown : null
)

const timeTrendIcon = computed(() => 
  timeTrend.value > 0 ? ArrowUp : timeTrend.value < 0 ? ArrowDown : null
)

// 方法
const loadData = async (id: number) => {
  try {
    let result=await readingDataService(id)
    const mockData=result.data
    totalBooks.value = mockData.totalBooks
    readingDays.value = mockData.readingDays
    totalHours.value = mockData.totalHours
    currentStreak.value = mockData.currentStreak
    booksTrend.value = mockData.booksTrend
    timeTrend.value = mockData.timeTrend
    currentMonth.value = mockData.currentMonth
    efficiencyScore.value = mockData.efficiencyScore
    concentrationScore.value = mockData.concentrationScore
    comprehensionScore.value = mockData.comprehensionScore
    speedScore.value = mockData.speedScore
    genreData.value = mockData.genreData
    timeData.value = mockData.timeData

    // 更新图表
    updateCharts()
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const initCharts = () => {
  // 初始化趋势图表
  const trendChartEl = document.getElementById('readingTrendChart')
  if (trendChartEl) {
    trendChart = echarts.init(trendChartEl)
    updateTrendChart()
  }

  // 初始化饼图
  const pieChartEl = document.getElementById('genreDistributionChart')
  if (pieChartEl) {
    pieChart = echarts.init(pieChartEl)
    updatePieChart()
  }
}

const updateCharts = () => {
  updateTrendChart()
  updatePieChart()
}

const updateTrendChart = () => {
  if (!trendChart) return

  const option = {
    backgroundColor: '#fff',
    tooltip: {
      trigger: 'axis',
      formatter: '{b0}<br/>{a0}: {c0}分钟'
    },
    xAxis: {
      type: 'category',
      data: timeData.value.map(item => item.time),
      axisLine: {
        lineStyle: {
          color: '#ddd'
        }
      },
      axisLabel: {
        color: '#666',
        fontSize: 11
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        show: false
      },
      axisTick: {
        show: false
      },
      splitLine: {
        lineStyle: {
          color: '#f5f5f5'
        }
      },
      axisLabel: {
        color: '#666',
        fontSize: 11
      }
    },
    series: [{
      name: '阅读时长',
      type: 'line',
      smooth: true,
      data: timeData.value.map(item => item.value),
      itemStyle: {
        color: '#2A5CAA'
      },
      areaStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: 'rgba(42, 92, 170, 0.2)' },
          { offset: 1, color: 'rgba(42, 92, 170, 0.05)' }
        ])
      },
      lineStyle: {
        width: 2
      },
      symbolSize: 6
    }],
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '5%',
      containLabel: true
    }
  }

  trendChart.setOption(option)
}

const updatePieChart = () => {
  if (!pieChart) return

  const option = {
    backgroundColor: '#fff',
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}本 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 5,
      top: 'center',
      data: genreData.value.map(item => item.name),
      textStyle: {
        color: '#666',
        fontSize: 11
      },
      itemWidth: 10,
      itemHeight: 10
    },
    series: [{
      name: '书籍类型',
      type: 'pie',
      radius: ['45%', '65%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 3,
        borderColor: '#fff',
        borderWidth: 1
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '12',
          fontWeight: 'bold',
          formatter: '{b}\n{d}%'
        }
      },
      labelLine: {
        show: false
      },
      data: genreData.value.map((item, index) => ({
        value: item.value,
        name: item.name,
        itemStyle: {
          color: colors[index % colors.length]
        }
      }))
    }]
  }

  pieChart.setOption(option)
}

const changeTimeRange = (range: 'week' | 'month' | 'year') => {
  timeRange.value = range
  // 这里应该重新加载数据
  loadTimeData(range)
}

const refreshScore = () => {
  // 模拟重新评估
  efficiencyScore.value = Math.min(100, efficiencyScore.value + Math.floor(Math.random() * 5))
  concentrationScore.value = Math.min(10, concentrationScore.value + 0.5)
  comprehensionScore.value = Math.min(10, comprehensionScore.value + 0.3)
  speedScore.value = Math.min(500, speedScore.value + 20)
}

const getProgressColor = (score: number) => {
  if (score >= 8) return '#4ECB73'
  if (score >= 5) return '#FFC107'
  return '#FF6B6B'
}

const getSpeedColor = (speed: number) => {
  if (speed >= 400) return '#4ECB73'
  if (speed >= 250) return '#FFC107'
  return '#FF6B6B'
}

// 返回按钮点击事件
const goBack = () => {
  router.push('/user')
}

//定义路径参数
const route=useRoute()
// 生命周期
onMounted(() => {
  loadData(route.query.id)
  // 使用nextTick确保DOM已渲染
  setTimeout(initCharts, 300)
})
</script>

<template>
  <div class="reading-analytics">
    <!-- 返回按钮 -->
    <div class="back-button">
      <el-button 
        type="text" 
        icon="ArrowLeft" 
        @click="goBack"
        class="back-btn"
      >
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>

    <!-- 头部统计卡片 -->
    <div class="stats-header">
      <el-card class="stat-card" shadow="hover" @click="navigateToBooks">
        <div class="stat-value">{{ totalBooks }}</div>
        <div class="stat-label">已读书籍</div>
        <div class="stat-trend" :class="{ 'up': booksTrend > 0, 'down': booksTrend < 0 }">
          <el-icon v-if="booksTrendIcon" :size="12">
            <component :is="booksTrendIcon" />
          </el-icon>
          <span>{{ Math.abs(booksTrend) }}%</span>
        </div>
      </el-card>

      <el-card class="stat-card highlight" shadow="hover" @click="navigateToCalendar">
        <div class="stat-value">{{ readingDays }}</div>
        <div class="stat-label">阅读天数</div>
        <div class="streak-badge">
          <el-icon :size="12">
            <StarFilled />
          </el-icon>
          <span>连续{{ currentStreak }}天</span>
        </div>
      </el-card>

      <el-card class="stat-card" shadow="hover" @click="navigateToTime">
        <div class="stat-value">{{ totalHours }}h</div>
        <div class="stat-label">阅读时长</div>
        <div class="stat-trend" :class="{ 'up': timeTrend > 0, 'down': timeTrend < 0 }">
          <el-icon v-if="timeTrendIcon" :size="12">
            <component :is="timeTrendIcon" />
          </el-icon>
          <span>{{ Math.abs(timeTrend) }}%</span>
        </div>
      </el-card>
    </div>

    <!-- 阅读趋势图表 -->
    <el-card class="chart-section" shadow="hover">
      <div class="section-header">
        <span>阅读趋势</span>
      </div>
      <div class="chart-container">
        <div id="readingTrendChart" class="chart" style="width: 100%; height: 250px;"></div>
      </div>
    </el-card>

    <!-- 书籍类型分布 -->
    <el-card class="distribution-section" shadow="hover">
      <div class="section-header">
        <span>书籍类型分布</span>
        <div class="view-more" @click="navigateToGenres">
          <span>查看详情</span>
          <el-icon :size="12">
            <Forward />
          </el-icon>
        </div>
      </div>
      <div class="chart-container">
        <div id="genreDistributionChart" class="chart" style="width: 100%; height: 250px;"></div>
      </div>
      <div class="legend">
        <div v-for="(item, index) in genreData" :key="index" class="legend-item">
          <div class="legend-color" :style="{ backgroundColor: colors[index] }"></div>
          <span>{{ item.name }} {{ item.percentage }}%</span>
          <span class="book-count">{{ item.value }}本</span>
        </div>
      </div>
    </el-card>

    <!-- 阅读时段分析 -->
    <el-card class="time-section" shadow="hover">
      <div class="section-header">
        <span>阅读时段分布</span>
        <div class="time-filter">
          <span
            v-for="range in ['week', 'month', 'year']"
            :key="range"
            :class="{ active: timeRange === range }"
            @click="changeTimeRange(range as any)"
          >
            {{ range === 'week' ? '本周' : range === 'month' ? '本月' : '全年' }}
          </span>
        </div>
      </div>
      <div class="time-grid">
        <div v-for="(item, index) in timeData" :key="index" class="time-item">
          <span class="time-label">{{ item.time }}</span>
          <div class="time-bar-container">
            <div
              class="time-bar"
              :style="{
                width: `${item.percentage}%`,
                backgroundColor: timeColors[index % timeColors.length]
              }"
            ></div>
          </div>
          <span class="time-percentage">{{ item.percentage }}%</span>
        </div>
      </div>
    </el-card>

    <!-- 阅读效率评分 -->
    <el-card class="score-section" shadow="hover">
      <div class="section-header">
        <span>阅读效率评分</span>
        <div class="refresh-btn" @click="refreshScore">
          <el-icon :size="14">
            <Refresh />
          </el-icon>
          <span>更新评估</span>
        </div>
      </div>
      <div class="score-container">
        <div class="gauge-chart">
          <div class="gauge-background"></div>
          <div
            class="gauge-mask"
            :style="{ transform: `rotate(${efficiencyScore * 1.8}deg)` }"
          ></div>
          <div class="gauge-score">{{ efficiencyScore }}</div>
          <div class="gauge-label">效率评分</div>
        </div>
        <div class="score-details">
          <div class="detail-item">
            <span class="detail-label">专注度</span>
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{
                  width: `${concentrationScore * 10}%`,
                  backgroundColor: getProgressColor(concentrationScore)
                }"
              ></div>
            </div>
            <span class="detail-value">{{ concentrationScore }}/10</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">阅读速度</span>
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{
                  width: `${Math.min(speedScore / 5, 100)}%`,
                  backgroundColor: getSpeedColor(speedScore)
                }"
              ></div>
            </div>
            <span class="detail-value">{{ speedScore }}字/分钟</span>
          </div>
          <div class="detail-item">
            <span class="detail-label">理解度</span>
            <div class="progress-bar">
              <div
                class="progress-fill"
                :style="{
                  width: `${comprehensionScore * 10}%`,
                  backgroundColor: getProgressColor(comprehensionScore)
                }"
              ></div>
            </div>
            <span class="detail-value">{{ comprehensionScore }}/10</span>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.reading-analytics {
  padding: 10px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.back-button {
  margin-bottom: 10px;
  
  .back-btn {
    color: #2A5CAA;
    font-size: 13px;
    display: flex;
    align-items: center;
    padding: 0;
    
    .el-icon {
      margin-right: 4px;
    }
    
    &:hover {
      color: #1a4c8a;
    }
  }
}

.stats-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  gap: 8px;

  .stat-card {
    flex: 1;
    background-color: #fff;
    border-radius: 8px;
    padding: 10px;
    text-align: center;
    position: relative;
    overflow: hidden;
    cursor: pointer;
    transition: transform 0.3s, box-shadow 0.3s;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
    }

    &.highlight {
      background-color: #2A5CAA;
      color: #fff;

      .stat-value,
      .stat-label {
        color: #fff;
      }

      .streak-badge {
        background-color: rgba(255, 255, 255, 0.2);
        color: #fff;
      }
    }

    .stat-value {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-bottom: 3px;
    }

    .stat-label {
      font-size: 11px;
      color: #666;
      margin-bottom: 5px;
    }

    .stat-trend {
      font-size: 11px;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 3px;

      &.up {
        color: #4ECB73;
      }

      &.down {
        color: #FF6B6B;
      }
    }

    .streak-badge {
      display: inline-flex;
      align-items: center;
      padding: 1px 5px;
      border-radius: 8px;
      background-color: #f0f0f0;
      font-size: 11px;
      color: #666;
      margin-top: 5px;

      .el-icon {
        margin-right: 2px;
      }
    }
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 15px 0 10px;
  font-size: 14px;
  font-weight: bold;
  color: #333;

  .view-more {
    display: flex;
    align-items: center;
    font-size: 11px;
    color: #2A5CAA;
    cursor: pointer;

    .el-icon {
      margin-left: 2px;
    }
  }

  .refresh-btn {
    display: flex;
    align-items: center;
    font-size: 11px;
    color: #2A5CAA;
    cursor: pointer;

    .el-icon {
      margin-right: 2px;
    }
  }

  .time-filter {
    display: flex;
    font-size: 11px;
    gap: 8px;

    span {
      padding: 1px 5px;
      border-radius: 3px;
      color: #666;
      cursor: pointer;

      &.active {
        background-color: #2A5CAA;
        color: #fff;
      }
    }
  }
}

.chart-section,
.distribution-section,
.time-section,
.score-section {
  background-color: #fff;
  border-radius: 8px;
  padding: 10px;
  margin-bottom: 10px;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05);
}

.chart-container {
  width: 100%;
  height: 250px;

  .chart {
    width: 100%;
    height: 100%;
  }
}

.legend {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-top: 10px;
  gap: 8px;

  .legend-item {
    display: flex;
    align-items: center;
    width: calc(50% - 4px);
    margin-bottom: 8px;
    font-size: 11px;
    padding: 3px;
    border-radius: 3px;
    cursor: pointer;

    &:hover {
      background-color: #f5f5f5;
    }

    .legend-color {
      width: 10px;
      height: 10px;
      border-radius: 2px;
      margin-right: 6px;
    }

    .book-count {
      margin-left: auto;
      color: #999;
    }
  }
}

.time-grid {
  .time-item {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    padding: 5px 0;
    cursor: pointer;

    &:hover {
      background-color: #f8f8f8;
      border-radius: 5px;
    }

    .time-label {
      width: 80px;
      font-size: 12px;
      color: #666;
    }

    .time-bar-container {
      flex: 1;
      height: 6px;
      background-color: #eee;
      border-radius: 3px;
      margin: 0 8px;
      overflow: hidden;

      .time-bar {
        height: 100%;
        border-radius: 3px;
        transition: width 0.3s ease;
      }
    }

    .time-percentage {
      width: 35px;
      text-align: right;
      font-size: 12px;
      color: #666;
    }
  }
}

.score-container {
  display: flex;
  gap: 10px;

  .gauge-chart {
    position: relative;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    .gauge-background {
      position: absolute;
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background: conic-gradient(
        #4ECB73 0%,
        #A5D6A7 25%,
        #FFC107 50%,
        #FFAB91 75%,
        #FF6B6B 100%
      );
      z-index: 0;
    }

    .gauge-mask {
      position: absolute;
      width: 96px;
      height: 96px;
      background-color: #fff;
      border-radius: 50%;
      top: 12px;
      left: 12px;
      transform-origin: center;
      z-index: 1;
      transition: transform 0.6s ease;
    }

    .gauge-score {
      font-size: 22px;
      font-weight: bold;
      color: #333;
      z-index: 2;
    }

    .gauge-label {
      font-size: 11px;
      color: #666;
      z-index: 2;
      margin-top: 3px;
    }
  }

  .score-details {
    flex: 1;

    .detail-item {
      display: flex;
      align-items: center;
      margin-bottom: 8px;

      .detail-label {
        width: 55px;
        font-size: 12px;
        color: #666;
      }

      .progress-bar {
        flex: 1;
        height: 5px;
        background-color: #eee;
        border-radius: 2.5px;
        margin: 0 8px;
        overflow: hidden;

        .progress-fill {
          height: 100%;
          border-radius: 2.5px;
          transition: width 0.3s ease;
        }
      }

      .detail-value {
        width: 60px;
        font-size: 12px;
        color: #333;
        text-align: right;
      }
    }
  }
}
</style>